/** 通信通道 */

export interface IAisleOptions {

    /** app id */
    id: string;

    /** app 的window */
    appWindow: Window;

    /** app 的容器 */
    appHead: HTMLElement;
}

export default class Aisle {

    /** sdk 的容器 */
    top: Window = window;

    /** app 的window */
    appWindow: Window;

    /** app 的容器 */
    appHead: HTMLElement;

    /** 应用ID */
    id: string;

    constructor(options: IAisleOptions) {
        this.id = options.id;
        this.appWindow = options.appWindow;
        this.appHead = options.appHead;
        this.appWindow['$_MicAisle'] = this;
    }

    get micPack() {
        return this.appWindow['$_MicPack'];
    }

    /** 调用应用的方法 */
    call = async (id: string, fnName: string, ...parameter: any[]) => {
        try {
            const iframe = window.document.querySelector(`#mic-head>#${id.replace(/\./g, '\\.')}>iframe`) as HTMLIFrameElement;
            if (iframe && iframe.contentWindow) {
                const fn = iframe.contentWindow['$_Export'][fnName] as Function;
                return await fn.apply(null, parameter);
            }
        } catch (error) {
        }
    }

    /** 转移CSS */
    moveCss = async () => {
        if (!this.appWindow || !this.appHead) return;

        let linkList = this.appWindow.document.querySelectorAll('link');
        for (let i = 0; i < linkList.length; i++) {
            await loadCss(linkList[i], this.appHead);
        }

        this.appWindow.document.querySelectorAll('style').forEach(e => {
            this.appHead?.appendChild(e);
        })
    }
}

const loadCss = (e: HTMLLinkElement, head: HTMLElement) => {
    return new Promise<void>(resolve => {

        e.parentNode?.removeChild(e);

        const link = document.createElement('link');
        link.href = e.href;
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.onload = () => { resolve() }
        head.appendChild(link);
    })
}